package controller

import (
	"errors"
	"github.com/balance_foods/common"
	"github.com/balance_foods/global"
	"github.com/balance_foods/middleware"
	"github.com/balance_foods/model/foods"
	user2 "github.com/balance_foods/model/user"
	"github.com/balance_foods/router"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

const dailyFoods = "daily"

type DailyApi struct {
}

func init() {

	dailyApi := DailyApi{}

	group := router.Router.Group(dailyFoods, middleware.Cors())

	{
		group.POST("add", middleware.JWTAuthMiddleware(), dailyApi.Add)

		group.POST("dayDetail", middleware.JWTAuthMiddleware(), dailyApi.ListDayDetail)

		group.POST("dateList", middleware.JWTAuthMiddleware(), dailyApi.DateList)

		group.POST("recommend", middleware.JWTAuthMiddleware(), dailyApi.Recommend)

	}
}

func (DailyApi) Recommend(ctx *gin.Context) {

	userId := ctx.GetInt("uid")

	var user user2.User

	user.Id = userId

	err := global.Db.First(&user).Error

	if errors.Is(err, gorm.ErrRecordNotFound) {

		common.FailWithErr(err, ctx)

		return

	}

	foodDest := []foods.DailyFood{}

	global.Db.Raw("SELECT * from daily_foods where DATE(created_at) = DATE(NOW())  user_id = ? ", userId).Find(&foodDest)

	var aminot = 0

	var diet = 0

	var fatt = 0

	var proteint = 0

	var sact = 0

	var mealt = 0

	var vatt = 0

	var watert = 0

	for _, item := range foodDest {

		itm := foods.Category{}

		err = global.Db.First(&itm).Error

		if errors.Is(err, gorm.ErrRecordNotFound) {
			continue
		}
		weight := item.Weight

		amino := itm.AminoAcid
		die := itm.DietaryFiber
		fat := itm.Fat
		protein := itm.Protein
		sac := itm.Saccharine
		water := itm.Water
		vat := itm.Vitamin
		meal := itm.Minerals

		var total = amino + die + fat + protein + sac + water + vat

		aminot += weight * (amino / total)

		fatt += weight * (fat / total)

		diet += weight * (die / total)

		proteint += weight * (protein / total)

		sact += weight * (sac / total)

		watert += weight * (water / total)

		vatt += weight * (vat / total)

		meal += weight * (meal / total)

	}

	var sex = user.Sex

	var age1 = user.Age

	var style = user.Style

	var age = 0

	if age1 <= 12 {
		age = 11
	}
	if 12 <= age1 && age1 <= 17 {
		age = 17
	}
	if age1 > 18 {
		age = 18
	}
	var stand foods.Stand

	err = global.Db.Where("gender=? and age=? and mode = ? ", sex, age, style).First(&stand).Error

	if errors.Is(err, gorm.ErrRecordNotFound) {

		common.FailWithMessage("对应的模式不存在", ctx)

		return

	}

	sac2 := stand.Saccharine
	water2 := stand.Water
	fat2 := stand.Fat
	pro2 := stand.Protein
	die2 := stand.DietaryFiber
	ami2 := stand.AminoAcid
	vit2 := stand.Vitamin
	mine2 := stand.Minerals

	var data = make(map[string]interface{})

	var subDate = make(map[string]interface{})

	var result = make(map[string]interface{})

	if sac2 > sact {
		var foodCategoryList []foods.Category
		global.Db.Model(foods.Category{}).Order(" saccharine desc").Limit(3).Find(&foodCategoryList)

		data["蔗糖"] = foodCategoryList
	}
	subDate["蔗糖"] = sac2 - sact

	if water2 > watert {
		var foodCategoryList1 []foods.Category
		global.Db.Model(foods.Category{}).Order(" water desc").Limit(3).Find(&foodCategoryList1)
		data["水"] = foodCategoryList1
	}
	subDate["水"] = water2 - watert
	if fat2 > fatt {
		var foodCategoryList2 []foods.Category
		global.Db.Model(foods.Category{}).Order(" fat desc").Limit(3).Find(&foodCategoryList2)
		data["脂肪"] = foodCategoryList2
	}
	subDate["脂肪"] = fat2 - fatt
	if pro2 > proteint {
		var foodCategoryList3 []foods.Category
		global.Db.Model(foods.Category{}).Order(" protein desc").Limit(3).Find(&foodCategoryList3)
		data["蛋白质"] = foodCategoryList3
	}
	subDate["蛋白质"] = pro2 - proteint

	if die2 > diet {
		var foodCategoryList4 []foods.Category
		global.Db.Model(foods.Category{}).Order(" dietary_fiber desc").Limit(3).Find(&foodCategoryList4)
		data["膳食纤维"] = foodCategoryList4
	}

	subDate["膳食纤维"] = die2 - diet

	if ami2 > aminot {
		var foodCategoryList5 []foods.Category
		global.Db.Model(foods.Category{}).Order(" amino_acid desc").Limit(3).Find(&foodCategoryList5)
		data["氨基酸"] = foodCategoryList5
	}

	subDate["氨基酸"] = ami2 - aminot

	if vit2 > vatt {
		var foodCategoryList6 []foods.Category
		global.Db.Model(foods.Category{}).Order(" vitamin desc").Limit(3).Find(&foodCategoryList6)
		data["维他命"] = foodCategoryList6
	}
	subDate["维他命"] = vit2 - vatt
	if mine2 > mealt {
		var foodCategoryList7 []foods.Category
		global.Db.Model(foods.Category{}).Order(" minerals desc").Limit(3).Find(&foodCategoryList7)
		data["矿物质"] = foodCategoryList7
	}
	subDate["矿物质"] = mine2 - mealt

	result["lacDatas"] = data
	result["moreDatas"] = subDate
	common.SuccessWithData(result, ctx)

	return

}

func (DailyApi) DateList(ctx *gin.Context) {

	pageRequest := common.PageRequest{}

	err := ctx.ShouldBindJSON(&pageRequest)

	if err != nil {

		common.FailWithErr(err, ctx)

		return

	}

	uid := ctx.GetInt("uid")

	var list []foods.DateResponse

	global.Db.Raw(`SELECT
		  date(df.created_at) AS date,
		  SUM(df.weight) AS total
		FROM
		  daily_foods  df inner  join categories ca
		on df.category_id = ca.id
		where  df.user_id = ?
		group by date(df.created_at)
		order by  date(df.created_at)`, uid).Scan(&list)

	if list == nil {

		list = []foods.DateResponse{}

	}
	common.SuccessWithData(list, ctx)

}

func (DailyApi) List(ctx *gin.Context) {

	var pageRequest common.PageRequest

	err := ctx.ShouldBindJSON(&pageRequest)

	if err != nil {

		common.FailWithErr(err, ctx)

		return

	}

}

func (DailyApi) Add(ctx *gin.Context) {

	var addDaly foods.AddDaily

	err := ctx.ShouldBindJSON(&addDaly)

	if err != nil {
		common.FailWithErr(err, ctx)
		return
	}

	uid := ctx.GetInt("uid")

	var dalyFoods foods.DailyFood

	dalyFoods.CategoryId = addDaly.CategoryId

	dalyFoods.UserId = uid

	dalyFoods.Weight = addDaly.Weight

	global.Db.Save(&dalyFoods)

	common.SuccessWithMessage("添加成功", ctx)

}

func (DailyApi) ListDayDetail(ctx *gin.Context) {

	var dateDetail foods.DateDetail

	err := ctx.ShouldBindJSON(&dateDetail)

	if err != nil {
		common.FailWithErr(err, ctx)
		return
	}

	var dailyFoodsList []foods.DailyFood

	global.Db.Where("date(created_at) = ? ", dateDetail.Date).Find(&dailyFoodsList)

	if dailyFoodsList == nil {

		dailyFoodsList = []foods.DailyFood{}

	}

	var list []foods.DateDetailResponse

	for _, item := range dailyFoodsList {

		categoryId := item.CategoryId

		var itm foods.Category

		itm.Id = categoryId

		err = global.Db.First(&itm).Error

		if !errors.Is(err, gorm.ErrRecordNotFound) {

			var iitm = foods.DateDetailResponse{
				Base:         item.Base,
				CategoryId:   item.CategoryId,
				UserId:       item.UserId,
				Weight:       item.Weight,
				FoodCategory: itm,
			}

			list = append(list, iitm)

		}

	}

	common.SuccessWithData(list, ctx)

}
